import { defineStore } from "pinia";
import { ref } from 'vue'
import request from '@/utils/request'
import { ElMessage } from "element-plus";
export const usePersonStore = defineStore('PersonStore', () => {
    const changeFlag = ref(false)
    const changeMsg = ref('修改状态')
    const {username} = JSON.parse(localStorage.getItem('userInfo') ? localStorage.getItem('userInfo') : '{"nickname":"null","avatarUrl":"https://blog.znxs.vip/znxs/1E228F4E1015CF258706A7F3602F213C.jpg"}')
    const userInfo = ref({})
    const imgIsShow = ref(true)
    const getUserInfo = async ()=>{
        const {data} = await request.get(`/user/person/${username}`)
        userInfo.value = data
    }
    getUserInfo()
    const changeUserInfo = ()=>{
        changeFlag.value = !changeFlag.value
        changeFlag.value? changeMsg.value='保存信息':changeMsg.value='修改状态'
        imgIsShow.value = !changeFlag.value
        if(!changeFlag.value) {
            // 修改数据
            saveUserInfo()
            // 刷新内存的数据
            const localUser = JSON.parse(localStorage.getItem('userInfo'))
            localUser.nickname = userInfo.value.nickname
            localUser.avatarUrl = userInfo.value.avatarUrl?userInfo.value.avatarUrl:localUser.avatarUrl
            localStorage.setItem('userInfo',JSON.stringify(localUser))
        }
        if(!changeFlag.value) ElMessage({type:'success',message:'保存成功',grouping:true})
    }
    const saveUserInfo = async ()=>{
        await request.post('/user',userInfo.value)
        location.reload()
    } 
    const handleAvatarSuccess = async (file)=>{
        userInfo.value.avatarUrl = file
        imgIsShow.value = true
        ElMessage.success('文件上传成功')
    }
    return {
        changeFlag,
        changeMsg,
        userInfo,
        imgIsShow,
        getUserInfo,
        changeUserInfo,
        handleAvatarSuccess
    }
})